
#include <vector>

#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>

#include "bocat/common/base64.hpp"

#include "fc_indexiter.hpp"

namespace	fekcab	{

FileCellIndexIterator::FileCellIndexIterator( const char* filename )
		:	_ifs( filename )
{
}

FileCellIndexIterator::~FileCellIndexIterator()
{
	if ( _ifs.is_open() ) {
		_ifs.close();
	}
}


///////////////////////////////////////////////////////////////////////
//


int	
FileCellIndexIterator::next( std::string& kpin, std::string& skey, std::string& key, Timestamp& ts, std::string& op )
{
	if ( !_ifs ) {
		return	0;
	}
	if ( !_ifs.is_open() ) {
		return	0;
	}
	if ( _ifs.eof() ) {
		return	0;
	}

	while ( !_ifs.eof() ) {
		std::string line;
		std::getline( _ifs, line );
		boost::trim( line );

		// 
		// Field-ID     0       1      2     3           4         5          6    7
		// Field-Name tv_sec  tv_usec  op  skey_b64  kpin_b64  prev_loc_b64  key  data 
		std::vector< std::string >	fields;
		boost::split(fields, line, boost::is_any_of("\t"));
		if ( fields.size() != 8 ) {
			// just skip error lines
			continue;
		}
		const std::string&	tv_sec_s = fields[0];
		const std::string&	tv_usec_s = fields[1];

		struct	timeval	tv;
		tv.tv_sec = boost::lexical_cast< time_t >( tv_sec_s.c_str() );
		tv.tv_usec = boost::lexical_cast< suseconds_t >( tv_usec_s.c_str() );
		ts = Timestamp( tv );

		skey = bocat::common::base64_decode< std::string >( fields[ 3 ] );
		kpin = bocat::common::base64_decode< std::string >( fields[ 4 ] );
		key = fields[ 6 ];

		return	1;
	}

    return  0;  
}


}	//// namespace fekcab


